package com.swotxu.rttest.config;

import com.swotxu.rttest.annotation.MyLoadBalanced;
import com.swotxu.rttest.interceptor.MyInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Date: 2020/9/22 23:09
 * @Author: swotXu
 */
@Slf4j
@Configuration
public class MyAutoConfiguration {

    @Autowired(required = false)
    @MyLoadBalanced
    private List<RestTemplate> restTemplates = Collections.emptyList();

    @Bean
    public SmartInitializingSingleton myLoadBalancedRestTemplateInitializer(){
        log.info("===== 容器初始化注入 =====");
        return new SmartInitializingSingleton() {
            @Override
            public void afterSingletonsInstantiated() {
                for (RestTemplate myRt : restTemplates) {
                    // 获取 RestTemplate 原来所有的拦截器
                    List<ClientHttpRequestInterceptor> list = new ArrayList(myRt.getInterceptors());
                    // 增加自定义拦截器
                    list.add(new MyInterceptor());
                    // 重新设置到 RestTemplate
                    myRt.setInterceptors(list);
                }
            }
        };
    }
}
